#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能童话书增强版 - 主启动文件
整合所有模块，提供完整的增强功能
"""

import os
import sys
import json
import logging
from datetime import datetime
from flask import Flask, render_template, request, jsonify, session
from flask_cors import CORS
import secrets

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入自定义模块
try:
    from intelligent_story_engine import IntelligentStoryEngine, EmotionType
    from api_routes_enhanced import EnhancedStoryAPI
except ImportError as e:
    print(f"⚠️ 模块导入失败: {e}")
    print("正在使用基础模式...")

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/enhanced_app.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
CORS(app)

# 全局变量
story_engine = None
story_api = None
app_stats = {
    "total_stories": 0,
    "user_sessions": 0,
    "average_rating": 0.0,
    "start_time": datetime.now()
}

def initialize_enhanced_system():
    """初始化增强版系统"""
    global story_engine, story_api
    
    try:
        # 创建必要目录
        os.makedirs('logs', exist_ok=True)
        os.makedirs('static/js', exist_ok=True)
        os.makedirs('static/images', exist_ok=True)
        os.makedirs('templates', exist_ok=True)
        
        logger.info("🚀 正在初始化智能童话书增强版...")
        
        # 初始化智能故事引擎
        if 'IntelligentStoryEngine' in globals():
            story_engine = IntelligentStoryEngine()
            logger.info("✅ 智能故事生成引擎初始化完成")
        else:
            logger.warning("⚠️ 智能引擎模块未找到，使用基础模式")
        
        # 初始化API路由
        if 'EnhancedStoryAPI' in globals():
            story_api = EnhancedStoryAPI(story_engine, app_stats)
            logger.info("✅ 增强版API路由初始化完成")
        
        logger.info("🎭 智能童话书增强版初始化成功！")
        return True
        
    except Exception as e:
        logger.error(f"❌ 系统初始化失败: {e}")
        return False

@app.route('/')
def enhanced_index():
    """增强版主页"""
    try:
        # 生成用户会话ID
        if 'user_id' not in session:
            session['user_id'] = secrets.token_hex(8)
            app_stats["user_sessions"] += 1
            logger.info(f"👤 新用户会话: {session['user_id']}")
        
        # 准备模板数据
        template_data = {
            'stats': app_stats,
            'emotions': [e.value for e in EmotionType] if 'EmotionType' in globals() else ['friendship', 'courage', 'joy'],
            'system_info': {
                'engine_status': 'Enhanced' if story_engine else 'Basic',
                'features_count': 6,
                'version': '2.0'
            }
        }
        
        return render_template('index_enhanced.html', **template_data)
        
    except Exception as e:
        logger.error(f"❌ 主页加载失败: {e}")
        return f"<h1>应用加载失败</h1><p>错误信息: {e}</p>", 500

@app.route('/api/generate_story', methods=['POST'])
def api_generate_story():
    """智能故事生成API"""
    try:
        if story_api:
            return story_api.generate_intelligent_story()
        else:
            return generate_basic_story()
    except Exception as e:
        logger.error(f"❌ API调用失败: {e}")
        return jsonify({"success": False, "error": str(e)}), 500

@app.route('/api/rate_story', methods=['POST'])
def api_rate_story():
    """故事评分API"""
    try:
        if story_api:
            return story_api.rate_story()
        else:
            return jsonify({"success": True, "message": "评分已记录"})
    except Exception as e:
        logger.error(f"❌ 评分API失败: {e}")
        return jsonify({"success": False, "error": str(e)}), 500

@app.route('/api/system_status', methods=['GET'])
def api_system_status():
    """系统状态API"""
    try:
        if story_api:
            return story_api.get_system_status()
        else:
            return get_basic_status()
    except Exception as e:
        logger.error(f"❌ 状态API失败: {e}")
        return jsonify({"error": str(e)}), 500

def generate_basic_story():
    """基础故事生成（备用方案）"""
    try:
        data = request.get_json()
        theme = data.get("theme", "友谊")
        characters = data.get("characters", ["小兔子"])
        
        basic_story = {
            "title": f"{characters[0]}的{theme}故事",
            "story": f"""从前，有一只可爱的{characters[0]}，它住在美丽的森林里。

有一天，{characters[0]}决定去探索森林深处，寻找新的{theme}。在路上，它遇到了许多有趣的朋友和挑战。

通过勇气和智慧，{characters[0]}不仅找到了自己想要的{theme}，还学会了很多宝贵的道理。

从此以后，{characters[0]}生活得更加快乐和充实，成为了森林里最受欢迎的小动物。""",
            "characters": [{"name": char, "traits": ["善良", "勇敢", "聪明"]} for char in characters],
            "educational_insights": ["友谊的重要性", "勇气能克服困难", "善良会得到回报"],
            "quality_score": {"overall": 0.8},
            "generated_at": datetime.now().isoformat(),
            "metadata": {"engine": "Basic", "version": "1.0"}
        }
        
        app_stats["total_stories"] += 1
        
        return jsonify({
            "success": True,
            "data": basic_story,
            "message": "✅ 故事生成成功（基础模式）",
            "engine_type": "Basic Engine"
        })
        
    except Exception as e:
        logger.error(f"❌ 基础故事生成失败: {e}")
        return jsonify({"success": False, "error": str(e)}), 500

def get_basic_status():
    """获取基础系统状态"""
    uptime = (datetime.now() - app_stats["start_time"]).total_seconds()
    
    status = {
        "system_status": "运行正常",
        "engine_status": "增强引擎已就绪" if story_engine else "基础模式运行",
        "total_stories": app_stats["total_stories"],
        "user_sessions": app_stats["user_sessions"],
        "average_rating": round(app_stats["average_rating"], 2),
        "uptime_seconds": int(uptime),
        "uptime_formatted": f"{int(uptime//3600)}小时{int((uptime%3600)//60)}分钟",
        "features": [
            "📚 智能故事生成",
            "🎭 角色个性化",
            "💝 情感分析",
            "📊 质量评估",
            "⭐ 用户评分",
            "📈 实时统计"
        ],
        "timestamp": datetime.now().isoformat()
    }
    
    return jsonify(status)

if __name__ == '__main__':
    print("=" * 60)
    print("🎭 智能童话书增强版")
    print("🚀 正在启动增强版应用...")
    print("💡 集成智能故事引擎 + 情感分析 + 质量评估")
    print("=" * 60)
    
    if initialize_enhanced_system():
        print("✅ 系统初始化成功！")
        print("🌐 增强版访问地址: http://localhost:5001")
        print("📊 原版应用地址: http://localhost:5000")
        print("🎯 开始您的智能童话创作之旅！")
        print("=" * 60)
        
        try:
            app.run(host='0.0.0.0', port=5001, debug=True, threaded=True)
        except Exception as e:
            print(f"❌ 应用启动失败: {e}")
    else:
        print("❌ 初始化失败，请检查依赖和配置！")